(function (window,undefined) {
    // 记录游戏对象
    var that;
    /*
        map:地图对象
    */
    function Game(map) {
        //蛇对象
        this.snake = new Snake();
        //食物对象
        this.food = new Food();
        //地图对象
        this.map = map;
        //把游戏对象保存在全局变量that中
        that = this;
    }
    // 开始游戏
    Game.prototype.start = function () {
        this.snake.render(this.map);
        this.food.render(this.map);
        // 调用移动函数
        runSnake();
        // 注册键盘事件-控制移动方向
        bindKey();
       
    }
    //注册鼠标事件
    function bindKey() {
        document.addEventListener('keydown', function (event) {
            // 事件对象兼容处理
            event = window.event || event;
            switch (event.keyCode) {
                case 37:
                    that.snake.direction = 'left';
                    break;
                case 38:
                    that.snake.direction = 'top';
                    break;
                case 39:
                    that.snake.direction = 'right';
                    break;
                case 40:
                    that.snake.direction = 'bottom';
                    break;
            }
            
        }, false)
    }

    // 移动方法
    function runSnake() {
        var timerId = setInterval(function(){
            // 1-移动:仅仅修改蛇节坐标信息
            that.snake.move(that.food,that.map);
            // 2-控制蛇头不能走出地图
            var maxX=that.map.offsetWidth/that.snake.width; 
            var maxY=that.map.offsetHeight/that.snake.height; 
            var headX=that.snake.body[0].x;
            var headY=that.snake.body[0].y;
            //假设没有出界
            var flag=false;
            if(headX<0||headX>=maxX){
                flag=true;
                alert('game over!!!');
                // Tools.alert('game over!!!');
                clearInterval(timerId);
            }
            if(headY<0||headY>=maxY){
                flag=true;
                alert('game over!!!');
                // Tools.alert('game over!!!');
                clearInterval(timerId);
            }
            //只有当蛇头没有出界的时候,才移除页面上原来的蛇;重新绘制一条蛇
            if(!flag){
                //3-移除之前的蛇(在前))
                that.snake.remove();
                // 4-重新在页面上绘制一条蛇(在后)
                that.snake.render(that.map);
            }
            

        }, 150);
    }


    window.Game = Game;
})(window,undefined);